package sf.database.dialect.sqlserver;

import com.querydsl.sql.SQLServer2012Templates;
import com.querydsl.sql.SQLTemplates;
import sf.database.dialect.Keywords;

public class SQLServer2012Dialect extends SQLServer2008Dialect {
    private static SQLTemplates sqlTemplates = SQLServer2012Templates.DEFAULT;

    public SQLTemplates getQueryDslDialect() {
        return sqlTemplates;
    }

    public SQLServer2012Dialect() {
        this.keywords.addAll(Keywords.SQLSERVER2008);
    }

    @Override
    public String sqlPageList(String sql, long offset, int limit) {
        StringBuilder sb = new StringBuilder();
        sb.append(sql);
        //sqlserver 2012 以上的 offset 分页必须要跟在order by后面，因此如果语句本身没有order by则为其添加一个按默认时间戳的order by
        if (!sql.matches("(?i).* order by[^)]+$")) {
            sb.append(" order by current_timestamp");
        }
        if (offset < 0) {
            offset = 0;
        }
        sb.append(" OFFSET ").append(offset).append(" ROW FETCH NEXT ").append(limit).append(" rows only");
        return sb.toString();
    }
}
